package com.syni.mdd.sjb.common.datatreaure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppSmsService;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserChannel;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserSms;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.mapper.DxshAppUserSmsMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mdd.sjb.common.dxshapp.CommonPushToDsxhAppDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.GetMddBusinessDataByDxshAppDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.BusinessRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.dto.minapp.MinAppDto;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.sms.SmsDataRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.userChannel.SwitchChannelSmsNoticeRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.BaseRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.userChannel.SwitchChannelSmsNoticeVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2020-04-30
 */
@Service
public class DxshAppUserSmsServiceImpl extends ServiceImpl<DxshAppUserSmsMapper, DxshAppUserSms> implements DxshAppUserSmsService {

    @Autowired
    DxshAppUserSmsMapper dxshAppUserSmsMapper;

    @Autowired
    DxshAppSmsServiceService dxshAppSmsServiceService;

    @Autowired
    DxshAppUserChannelService dxshAppUserChannelService;

    @Autowired
    BusinessRestService businessRestService;

    @Autowired
    UserRestService userRestService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    DxshAppNewsService dxshAppNewsService;

    final int initDefaultSmsNum = 0;

    @Value("${business.sms.tip:100}")
    private Integer businessSmsTip;

    @Override
    public void intoUserSms(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppUserSms.USER_ID, userId);
        DxshAppUserSms dxshAppUserSms = dxshAppUserSmsMapper.selectOne(queryWrapper);
        if (dxshAppUserSms == null) {
            dxshAppUserSms = new DxshAppUserSms();
            dxshAppUserSms.setUserId(userId);
            dxshAppUserSms.setIsNotice(Constants.COMMON_FLAG_FALSE_INT);
            dxshAppUserSms.setSmsNum(initDefaultSmsNum);
            dxshAppUserSmsMapper.insert(dxshAppUserSms);
        }
    }

    @Override
    public Map<String, Object> data(BaseRqVo baseRqVo) {
        SmsDataRpVo smsDataRpVo = new SmsDataRpVo();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppUserSms.USER_ID, baseRqVo.getUserId());
        DxshAppUserSms dxshAppUserSms = this.getOne(queryWrapper);
        if (dxshAppUserSms == null) {
            return ResultMapHelper.failure("对不起，找不到记录");
        }
        Integer businessRole = bmsDxClientRoleService.getRoleId(baseRqVo.getUserId());
        /*if(businessRole == Constants.MDD_DY_ROLE_ID){

            return ResultMapHelper.success(smsDataRpVo, "店员无权限");
        }*/

        SmsDataRpVo.UserSms userSms = BeanUtils.copyProperties(dxshAppUserSms, SmsDataRpVo.UserSms.class);
        queryWrapper.clear();
        queryWrapper.eq(DxshAppSmsService.IS_DELETE, Constants.COMMON_FLAG_FALSE_INT);
        List<DxshAppSmsService> dxshAppSmsServiceList = dxshAppSmsServiceService.list(queryWrapper);
        List<SmsDataRpVo.SmsService> smsServiceList = BeanUtils.copyList(dxshAppSmsServiceList, SmsDataRpVo.SmsService.class);
        List<SmsDataRpVo.ChannelList> channelList = new ArrayList<>();

        queryWrapper.clear();
        queryWrapper.eq(DxshAppUserChannel.USER_ID, baseRqVo.getUserId());
        queryWrapper.eq(DxshAppUserChannel.IS_FILL, Constants.COMMON_FLAG_TRUE_INT);
        queryWrapper.orderByDesc(DxshAppUserChannel.NEW_TIME);
        List<DxshAppUserChannel> dxshAppUserChanneList = dxshAppUserChannelService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppSmsServiceList)) {
            //先进行数据获取处理
            GetMddBusinessDataByDxshAppDto getMddBusinessDataByDxshAppDto = new GetMddBusinessDataByDxshAppDto();

            Set<Integer> businessIds = dxshAppUserChanneList.stream()
                    .filter(v -> DxshAppUserChannelService.CHANNEL_MDD == v.getChannel() && v.getBusinessId() != null)
                    .map(DxshAppUserChannel::getBusinessId).collect(Collectors.toSet());

            getMddBusinessDataByDxshAppDto.setBusinessIds(businessIds);
            RpcResponseVo rpcResponseVo = businessRestService.getMddBusinessDataByDxshApp(getMddBusinessDataByDxshAppDto);
            if (rpcResponseVo.isSuccess()) {
                getMddBusinessDataByDxshAppDto = rpcResponseVo.parseObject(GetMddBusinessDataByDxshAppDto.class);
                for (DxshAppUserChannel q : dxshAppUserChanneList) {
                    if (getMddBusinessDataByDxshAppDto.getBusinessDatas() != null) {
                        for (GetMddBusinessDataByDxshAppDto.BusinessDataDto dto : getMddBusinessDataByDxshAppDto.getBusinessDatas()) {
                            if (q.getChannel() == DxshAppUserChannelService.CHANNEL_MDD && q.getBusinessId().equals(dto.getBusinessId())) {
                                q.setVendorName(dto.getVendorName());
                            }
                        }
                    }

                }
            }

            Set<String> minAppIds = dxshAppUserChanneList.stream()
                    .filter(v -> DxshAppUserChannelService.CHANNEL_MINAPP == v.getChannel() && v.getMinAppId() != null)
                    .map(DxshAppUserChannel::getMinAppId).collect(Collectors.toSet());
            //Todo:获取鸿杰小程序接口....
            String url = AppConfig.getProperty("saas.dxshapp.center.service") + "/dxshApp/app/getByStoreIds";
            ;
            String token = RequestHeaderData.getRequestHeaderData().getString("token");
            RpcResponseVo minrpcResponseVo = userRestService.getMiniTokenByUserId_v2(baseRqVo.getUserId(), token);
            if (minrpcResponseVo.isSuccess()) {
                String minitoken = minrpcResponseVo.getData().toString();
                String requestBody = RestTemplateUtils.postForEntityForJsonByLoadBalanced(url, minAppIds, RestTemplateUtils.getSassHeader(minitoken));
                JSONObject userJson = JSON.parseObject(requestBody);
                if (userJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(userJson.getString("status"))) {
                    JSONObject result = (JSONObject) userJson.get("data");
                    if (result != null) {
                        Iterator<DxshAppUserChannel> it = dxshAppUserChanneList.iterator();
                        while (((Iterator) it).hasNext()) {
                            DxshAppUserChannel q = it.next();
                            if (q.getChannel() == DxshAppUserChannelService.CHANNEL_MINAPP && StringUtils.checkAnyNotNull(q.getMinAppId()) && result.containsKey(q.getMinAppId())) {
                                MinAppDto minAppDto = JSON.parseObject(result.getString(q.getMinAppId()), MinAppDto.class);

                                q.setVendorName(minAppDto.getName());
//                            q.setLoginUrl(minAppDto.getAppFace());
                                if (minAppDto.getStatus() != 6) {
                                    it.remove();
                                }
                            }
                        }

                    }


                }

            }
            channelList = BeanUtils.copyList(dxshAppUserChanneList, SmsDataRpVo.ChannelList.class);
        }


        smsDataRpVo.setUserSms(userSms);
        smsDataRpVo.setSmsServiceList(smsServiceList);
        smsDataRpVo.setChannelList(channelList);

        return ResultMapHelper.success(smsDataRpVo, ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> switchChannelSmsNotice(SwitchChannelSmsNoticeVo switchChannelSmsNoticeVo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppUserChannel.ID, switchChannelSmsNoticeVo.getId());
        queryWrapper.eq(DxshAppUserChannel.USER_ID, switchChannelSmsNoticeVo.getUserId());
        queryWrapper.eq(DxshAppUserChannel.IS_FILL, Constants.COMMON_FLAG_TRUE_INT);
        DxshAppUserChannel dxshAppUserChannel = dxshAppUserChannelService.getOne(queryWrapper);
        if (dxshAppUserChannel == null) {
            return ResultMapHelper.failure(ResultMsg.CODE_ERROR_05);
        }
        if (dxshAppUserChannel.getChannel() == DxshAppUserChannelService.CHANNEL_MINAPP) {
            return ResultMapHelper.failure("小程序不允许关闭");
        }
        if (dxshAppUserChannel.getIsSmsNotice() == Constants.COMMON_FLAG_FALSE_INT) {
            dxshAppUserChannel.setIsSmsNotice(Constants.COMMON_FLAG_TRUE_INT);
        } else {
            dxshAppUserChannel.setIsSmsNotice(Constants.COMMON_FLAG_FALSE_INT);
        }
        dxshAppUserChannelService.saveOrUpdate(dxshAppUserChannel);
        SwitchChannelSmsNoticeRpVo switchChannelSmsNoticeRpVo = BeanUtils.copyProperties(dxshAppUserChannel, SwitchChannelSmsNoticeRpVo.class);
        return ResultMapHelper.success(switchChannelSmsNoticeRpVo, ResultMsg.HAND_SUCCESS);
    }

    public void handleUserSmsServiceUse(Integer userId, Integer useNum){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppUserSms.USER_ID,userId);
        List<DxshAppUserSms> dxshAppUserSmses = dxshAppUserSmsMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppUserSmses)){
            DxshAppUserSms dxshAppUserSms = dxshAppUserSmses.get(0);
            synchronized (this) {
                dxshAppUserSms.setSmsNum(dxshAppUserSms.getSmsNum() - useNum);
                dxshAppUserSmsMapper.updateById(dxshAppUserSms);
                if (dxshAppUserSms.getSmsNum() <= businessSmsTip && dxshAppUserSms.getLessThanTip().equals(Constants.COMMON_FLAG_FALSE_INT)) {
                    //余额提醒
                    this.handleSmsTipLogic(dxshAppUserSms);
                }
            }
        }
    }

    private void handleSmsTipLogic(DxshAppUserSms dxshAppUserSms) {
        CommonPushToDsxhAppDto commonPushToDsxhAppDto = new CommonPushToDsxhAppDto();
        commonPushToDsxhAppDto.setType(Constants.APP_NEWS_SYSTEM);
        commonPushToDsxhAppDto.setAlert("您的短信剩余量小于100条，为避免影响用户使用店铺服务，请及时充值");
        commonPushToDsxhAppDto.setUserId(dxshAppUserSms.getUserId());
        commonPushToDsxhAppDto.setDescribes("短信购买提醒");
        commonPushToDsxhAppDto.setMainTitle("系统消息");
        commonPushToDsxhAppDto.setMessageType(Constants.DANK_OTHER_INFORM);
        commonPushToDsxhAppDto.setMessageSecondType(Constants.DANK_OTHER_INFORM_SYS_NOTIFICATION);
        Map<String,Object> content = new HashMap();
        content.put("newType","smsPurchase");
        commonPushToDsxhAppDto.setContent(JSON.toJSONString(content));
        RpcResponseVo rpcResponseVo = dxshAppNewsService.commonPushToDsxhApp_v2(commonPushToDsxhAppDto);
        if(rpcResponseVo.isSuccess()){
            dxshAppUserSms.setLessThanTip(Constants.COMMON_FLAG_TRUE_INT);
            dxshAppUserSmsMapper.updateById(dxshAppUserSms);
        }
    }

//    @Override
//    public Map<String, Object> switchUserSmsNotice(BaseRqVo baseRqVo) {
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq(DxshAppUserSms.USER_ID,baseRqVo.getUserId());
//        DxshAppUserSms dxshAppUserSms = dxshAppUserSmsMapper.selectOne(queryWrapper);
//        if(dxshAppUserSms.getIsNotice()==Constants.COMMON_FLAG_FALSE_INT){
//            dxshAppUserSms.setIsNotice(Constants.COMMON_FLAG_TRUE_INT);
//        }else{
//            dxshAppUserSms.setIsNotice(Constants.COMMON_FLAG_FALSE_INT);
//            //关闭的同时 也将用户旗下的店铺
//            queryWrapper.clear();
//            queryWrapper.eq(DxshAppUserChannel.USER_ID,baseRqVo.getUserId());
//            List<DxshAppUserChannel> dxshAppUserChannelList = dxshAppUserChannelService.list(queryWrapper);
//            dxshAppUserChannelList.forEach(e->{
//                e.setIsSmsNotice(Constants.COMMON_FLAG_FALSE_INT);
//            });
//            dxshAppUserChannelService.saveOrUpdateBatch(dxshAppUserChannelList);
//        }
//        this.saveOrUpdate(dxshAppUserSms);
//
//        return ResultMapHelper.success(dxshAppUserSms,ResultMsg.HAND_SUCCESS);
//    }

}
